# -*- coding: utf-8 -*-
'''
    date:2017-06-06 hqk
    task 相关类
'''
import json
import gearman
import datetime
from common.xms_json import MyJson

from config.setting import jobServerHost
import time


class TaskModel(object):
    def __init__(self):
            self.nextTaskTime = datetime.datetime.now()
            
    def initTimeInterVal(self, daysitv, hoursitv):
        self.taskInterval = datetime.timedelta(days = daysitv, hours = hoursitv)    
        
    def taskAction(self):
        while True:
            time.sleep(10)
            if datetime.datetime.now() > self.nextTaskTime:
                self.main()
                self.nextTaskTime = datetime.datetime.now() + self.taskInterval    
                
    def main(self):
        pass

class TaskProtocol(object):
        def __init__(self):
            pass
        @staticmethod
        def make_newadd_protocol(id, data):
            return {id:data}
            
        @staticmethod
        def parse_newadd_protocol(newRes):
            allRe = []
            for newRe in newRes:
                results = newRe.result
                state, resJ = MyJson.jsonLoads(newRe.result)
                if state == False:
                    continue
                allRe.append(resJ)
            return allRe
        
        
        '''
            status 1 商铺关闭 2 新增图片 3 商铺基本信息变更  4.推荐菜变更 5.经纬度变更 6评论变更
        '''
        @staticmethod
        def return_update_protocol(id, data, status):
            return json.dumps({id:{'status':status, 'data':data}})
            
        @staticmethod
        def make_update_protocol(ids):
            return ids 

class TaskStyle(object):
        def __init__(self):
            pass
        @staticmethod
        def task_style(taskName, taskData):
            return {'task':taskName, 'data': json.dumps(taskData)}


class TaskGearman(object):
    def __init__(self):
        self.client = None
        self.worker = None
    
    def client_init(self):
        self.client = gearman.GearmanClient(jobServerHost)

    def client_multiple_task(self, jobLists):
        resp = self.client.submit_multiple_jobs(jobLists, background=False)
        return resp
    
    def worker_init(self):
        self.worker = gearman.GearmanWorker(jobServerHost)

    def worker_register(self, taskName, taskFunc):
        print self.worker.register_task(taskName, taskFunc)
    
    def worker_start(self):
        self.worker.work()
    
    def parse_worker_reslt(self, reslt):
        pass
        
    
        
